<template>
  <div>
    <el-drawer
      :title="order_data.name + '订单财务记录'"
      :visible.sync="childFormVisible"
      :wrapper-closable="false"
      append-to-body
      size="60%"
      class="mt-dialog"
    >
      <div style="margin: 20px;">
        <el-form :model="temp" :rules="rules" label-position="right" label-width="120px" class="finance-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="交易日期" prop="transaction_date">
                <el-date-picker v-model="temp.transaction_date" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
              <el-form-item label="交易类型" prop="transaction_type">
                <el-select v-model="temp.transaction_type" placeholder="请选择交易类型" style="width: 100%">
                  <el-option
                    v-for="item in finance_transactiontypes"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="单号" prop="reference_number">
                <el-input v-model="temp.reference_number" style="width: 100%" />
              </el-form-item>
              <el-form-item label="金额" prop="amount">
                <el-input-number v-model="temp.amount" :precision="2" :step="0.1" style="width: 100%" />
              </el-form-item>
              <el-form-item label="货币" prop="currency">
                <el-row :gutter="10">
                  <el-col :span="16">
                    <el-select v-model="temp.currency" placeholder="请选择货币" style="width: 100%">
                      <el-option
                        v-for="currency in availableCurrencies"
                        :key="currency.code"
                        :label="`${currency.code} - ${currency.name}`"
                        :value="currency.code"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    <el-button
                      type="primary"
                      size="small"
                      icon="el-icon-refresh-right"
                      @click="handleCurrencyConvert"
                    >
                      换算CNY
                    </el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="收入|支出" prop="is_income">
                <el-switch
                  v-model="temp.is_income"
                  style="width: 100%; display: flex; justify-content: flex-start; align-items: center;"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="收入"
                  inactive-text="支出"
                />
              </el-form-item>
              <el-form-item label="财务类别" prop="category">
                <el-select v-model="temp.category" placeholder="请选择类别" style="width: 100%">
                  <el-option
                    v-for="item in finance_categories"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="支付方式" prop="payment_method">
                <el-input v-model="temp.payment_method" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="temp.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="已完成" value="completed" />
                  <el-option label="待处理" value="pending" />
                  <el-option label="已取消" value="cancelled" />
                </el-select>
              </el-form-item>

              <el-form-item label="供应商/客户" prop="vendor_or_customer">
                <el-input v-model="temp.vendor_or_customer" style="width: 100%" />
              </el-form-item>
              <el-form-item label="预期付款日期" prop="expected_payment_date">
                <el-date-picker v-model="temp.expected_payment_date" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
              <el-form-item label="实际付款日期" prop="actual_payment_date">
                <el-date-picker v-model="temp.actual_payment_date" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
              <el-form-item label="是否已对账" prop="is_reconciled">
                <el-switch v-model="temp.is_reconciled" style="width: 100%; display: flex; justify-content: flex-start; align-items: center;" />
              </el-form-item>
              <el-form-item label="对账日期" prop="reconciliation_date">
                <el-date-picker v-model="temp.reconciliation_date" type="date" placeholder="选择日期" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注" prop="notes">
            <el-input v-model="temp.notes" type="textarea" rows="4" />
          </el-form-item>
          <el-form-item label="关联文件" prop="crmfiles">
            <div v-if="temp.crmfiles && temp.crmfiles.length > 0" class="file-list-display">
              <div v-for="(item, index) in temp.crmfiles" :key="index" class="file-item">
                <el-image
                  v-if="item.content_type.indexOf('image') !== -1"
                  :src="item.url"
                  :preview-src-list="[item.url]"
                  class="file-icon"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('pdf') !== -1"
                  icon-class="pdf"
                  class="file-icon"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('xlsx') !== -1"
                  icon-class="xlsx"
                  class="file-icon"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('xls') !== -1"
                  icon-class="xls"
                  class="file-icon"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('zip') !== -1"
                  icon-class="zip"
                  class="file-icon"
                />
                <svg-icon
                  v-else
                  icon-class="document"
                  class="file-icon"
                />
                <div class="file-name">{{ item.filename }}</div>
              </div>
            </div>
            <crmfilequickuploader :default-expanded="true" @insert="handleInsertFile" />
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="center" class="form-footer">
          <el-button @click="childFormVisible = false;editloading=false;">取 消</el-button>
          <el-button type="primary" :loading="editloading" @click="confirm">确 定</el-button>
        </el-row>
      </div>
    </el-drawer>

    <!-- 汇率转换对话框 -->
    <el-dialog
      title="汇率转换"
      :visible.sync="convertDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="convertForm" :model="convertForm" label-width="120px">
        <el-form-item label="原始金额">
          <el-input-number
            v-model="convertForm.originalAmount"
            :precision="2"
            style="width: 100%;"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="原始货币">
          <el-input v-model="convertForm.originalCurrency" :disabled="true" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="目标货币">
          <el-select v-model="convertForm.targetCurrency" placeholder="请选择目标货币" style="width: 100%;">
            <el-option
              v-for="currency in availableCurrencies"
              :key="currency.code"
              :label="`${currency.code} - ${currency.name}`"
              :value="currency.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="汇率" prop="exchangeRate">
          <el-input-number
            v-model="convertForm.exchangeRate"
            :precision="4"
            :step="0.0001"
            :min="0"
            style="width: 100%;"
            placeholder="请输入汇率"
            @change="handleExchangeRateChange"
          />
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            汇率来源：{{ exchangeRateSource }}
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleConvertConfirm">计算转换</el-button>
        </el-form-item>
        <el-form-item v-if="convertResult" label="转换结果">
          <el-alert
            :title="`${convertResult.source_amount} ${convertResult.source_currency} = ${convertResult.target_amount} ${convertResult.target_currency}`"
            type="success"
            :closable="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="convertDialogVisible = false">取消</el-button>
        <el-button v-if="convertResult" type="primary" @click="handleApplyConversion">应用转换</el-button>
      </div>
    </el-dialog>

    <el-row style="justify-content: left;display: flex; ">
      <el-button size="mini" icon="el-icon-plus" round @click="handleShowEdit">添加财务记录</el-button>
    </el-row>

    <!-- 财务统计卡片 -->
    <el-row v-if="data.length > 0" :gutter="20" style="margin: 15px 0;">
      <el-col :span="6">
        <el-card shadow="hover" style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #67c23a;">
            +{{ financialSummary.totalIncome }}
          </div>
          <div style="color: #909399; font-size: 14px;">总收入 ({{ financialSummary.incomeCurrency }})</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #f56c6c;">
            -{{ financialSummary.totalExpense }}
          </div>
          <div style="color: #909399; font-size: 14px;">总支出 ({{ financialSummary.expenseCurrency }})</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold;" :style="{ color: financialSummary.netAmount >= 0 ? '#67c23a' : '#f56c6c' }">
            {{ financialSummary.netAmount >= 0 ? '+' : '' }}{{ financialSummary.netAmount }}
          </div>
          <div style="color: #909399; font-size: 14px;">净利润</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold;" :style="{ color: financialSummary.grossMarginRate >= 30 ? '#67c23a' : financialSummary.grossMarginRate >= 10 ? '#e6a23c' : '#f56c6c' }">
            {{ financialSummary.grossMarginRate }}%
          </div>
          <div style="color: #909399; font-size: 14px;">毛利率</div>
        </el-card>
      </el-col>
    </el-row>

    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      :default-sort="{prop: 'transaction_date', order: 'descending'}"
      style="width: 100%"
    >
      <el-table-column align="center" label="交易日期" prop="transaction_date" width="120" />
      <el-table-column align="center" label="交易类型/收支类型/类别" prop="transaction_type" width="200">
        <template slot-scope="scope">
          {{ scope.row.transaction_type }}/{{ scope.row.is_income ? '收入' : '支出' }}/{{ scope.row.category }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="金额" prop="amount" width="180">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center; gap: 5px;">
            <span :style="{ color: scope.row.is_income ? 'green' : 'red' }">
              {{ scope.row.is_income ? '+' : '-' }}{{ scope.row.amount }} {{ scope.row.currency }}
            </span>
            <el-button
              v-if="scope.row.currency !== 'CNY'"
              type="text"
              size="mini"
              icon="el-icon-refresh-right"
              title="换算为人民币"
              @click="handleTableRowConvert(scope.row)"
            >
              换算
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status" width="100">
        <template slot-scope="scope">
          {{ scope.row.status === 'completed' ? '已完成' : scope.row.status === 'pending' ? '待处理' : '已取消' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否已对账" prop="is_reconciled" width="120">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.is_reconciled" type="primary" size="mini" @click="handleReconciled(scope.row)">确认无误</el-button>
          <el-tag v-else size="mini">已对账</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="left" label="备注" prop="notes" min-width="200">
        <template slot-scope="scope">
          <div>
            <div v-if="scope.row.notes" style="margin-bottom: 5px;">
              {{ scope.row.notes }}
            </div>
            <div v-if="scope.row.vendor_or_customer" style="margin-bottom: 5px; font-size: 12px; color: #666;">
              供应商/客户：{{ scope.row.vendor_or_customer }}
            </div>
            <div v-if="scope.row.crmfiles && scope.row.crmfiles.length > 0" class="file-list-inline">
              <div
                v-for="(item, index) in scope.row.crmfiles"
                :key="index"
                class="file-item-inline"
                @mouseenter="handleImageHover(item, $event)"
                @mouseleave="hideImagePreview"
              >
                <el-image
                  v-if="item.content_type.indexOf('image') !== -1"
                  :src="item.url"
                  :preview-src-list="[item.url]"
                  class="file-icon-small"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('pdf') !== -1"
                  icon-class="pdf"
                  class="file-icon-small"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('xlsx') !== -1"
                  icon-class="xlsx"
                  class="file-icon-small"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('xls') !== -1"
                  icon-class="xls"
                  class="file-icon-small"
                />
                <svg-icon
                  v-else-if="item.filename.indexOf('zip') !== -1"
                  icon-class="zip"
                  class="file-icon-small"
                />
                <svg-icon
                  v-else
                  icon-class="document"
                  class="file-icon-small"
                />
                <span class="file-name-small">{{ item.filename }}</span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="单号" prop="reference_number" />
      <el-table-column align="center" label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditFromTable(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #909399;" @click="handleDeleteFromTable(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @current-change="handlePageChange"
      @size-change="handlePageChange"
    />

    <!-- 图片hover预览 -->
    <div
      v-if="imagePreview.visible"
      class="image-hover-preview"
      :style="{ left: imagePreview.x + 'px', top: imagePreview.y + 'px' }"
    >
      <img :src="imagePreview.src" :alt="imagePreview.alt">
    </div>
  </div>
</template>

<script>
import { Get, Post, Put, UserPutFinance } from '@/api/crm/crmorderfinance'
import { Get as GetExchangeRate } from '@/api/crm/crmexchangerate'
import { ShowProjectAttr } from '@/api/erp/elicink/project'
import qs from 'qs'
import Crmfilequickuploader from '../../../components/crmfilequickuploader'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Crmorderfinance',
  components: { Crmfilequickuploader },
  props: ['order_data'],
  data() {
    return {
      childFormVisible: false,
      listLoading: false,
      editloading: false,
      data: [],
      rules: {
        transaction_date: [{ required: true, message: '请选择交易日期', trigger: 'change' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
        // 添加其他必要的验证规则
      },
      action: 'create',
      temp: this.initTemp(),
      finance_categories: [],
      finance_transactiontypes: [],
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      pagesize: 20,
      page: 1,
      total: 0,
      fileList: [],
      convertDialogVisible: false,
      convertForm: {
        originalAmount: 0,
        originalCurrency: 'CNY',
        targetCurrency: 'CNY',
        exchangeRate: 1
      },
      imagePreview: {
        visible: false,
        src: '',
        alt: '',
        x: 0,
        y: 0
      },
      convertResult: null,
      availableCurrencies: [
        { code: 'USD', name: '美元' },
        { code: 'EUR', name: '欧元' },
        { code: 'GBP', name: '英镑' },
        { code: 'JPY', name: '日元' },
        { code: 'CNY', name: '人民币' },
        { code: 'CAD', name: '加拿大元' },
        { code: 'AUD', name: '澳大利亚元' },
        { code: 'CHF', name: '瑞士法郎' },
        { code: 'HKD', name: '港币' },
        { code: 'SGD', name: '新加坡元' },
        { code: 'KRW', name: '韩元' },
        { code: 'INR', name: '印度卢比' },
        { code: 'THB', name: '泰铢' },
        { code: 'MXN', name: '墨西哥比索' },
        { code: 'BRL', name: '巴西雷亚尔' },
        { code: 'SEK', name: '瑞典克朗' },
        { code: 'NOK', name: '挪威克朗' },
        { code: 'DKK', name: '丹麦克朗' },
        { code: 'PLN', name: '波兰兹罗提' },
        { code: 'CZK', name: '捷克克朗' },
        { code: 'HUF', name: '匈牙利福林' },
        { code: 'RUB', name: '俄罗斯卢布' },
        { code: 'ZAR', name: '南非兰特' },
        { code: 'TRY', name: '土耳其里拉' },
        { code: 'AED', name: '阿联酋迪拉姆' },
        { code: 'SAR', name: '沙特里亚尔' }
      ],
      currentConvertRow: null, // 新增属性，用于保存当前要转换的行数据
      exchangeRateSource: '本地配置' // 新增属性，用于显示汇率来源
    }
  },
  computed: {
    financialSummary() {
      if (!this.data || this.data.length === 0) {
        return {
          totalIncome: '0.00',
          totalExpense: '0.00',
          netAmount: '0.00',
          grossMarginRate: '0.00',
          incomeCurrency: 'CNY',
          expenseCurrency: 'CNY'
        }
      }

      const incomeData = this.data.filter(item => item.is_income)
      const expenseData = this.data.filter(item => !item.is_income)

      const totalIncome = incomeData.reduce((prev, curr) => prev + parseFloat(curr.amount || 0), 0)
      const totalExpense = expenseData.reduce((prev, curr) => prev + parseFloat(curr.amount || 0), 0)

      // 获取主要货币类型（出现次数最多的货币）
      const incomeCurrencies = incomeData.map(item => item.currency)
      const expenseCurrencies = expenseData.map(item => item.currency)
      const incomeCurrency = this.getMostFrequentCurrency(incomeCurrencies) || 'CNY'
      const expenseCurrency = this.getMostFrequentCurrency(expenseCurrencies) || 'CNY'

      const netAmount = totalIncome - totalExpense
      const grossMarginRate = totalIncome > 0 ? ((netAmount / totalIncome) * 100).toFixed(2) : '0.00'

      return {
        totalIncome: totalIncome.toFixed(2),
        totalExpense: totalExpense.toFixed(2),
        netAmount: netAmount.toFixed(2),
        grossMarginRate,
        incomeCurrency,
        expenseCurrency
      }
    }
  },
  watch: {
    order_data: {
      handler(v) {
        this.getList()
      },
      immediate: true
    },
    'convertForm.targetCurrency': function(newVal, oldVal) {
      if (newVal && newVal !== oldVal && this.convertForm.originalCurrency) {
        this.fetchExchangeRate(this.convertForm.originalCurrency, newVal)
      }
    }
  },
  created() {
    this.handleGetFinanceCategoy()
    this.handleGetFinanceTransactionTypes()
  },
  methods: {
    // 图片hover预览
    handleImageHover(file, event) {
      if (file.content_type && file.content_type.indexOf('image') !== -1) {
        const rect = event.currentTarget.getBoundingClientRect()

        // 默认显示在左上方
        let x = rect.left - 310 // 预览框宽度300px + 10px间距
        let y = rect.top

        // 如果左侧空间不够，显示在右侧
        if (x < 10) {
          x = rect.right + 10
        }

        // 如果下方空间不够，向上调整
        if (y + 400 > window.innerHeight) {
          y = Math.max(10, window.innerHeight - 410)
        }

        this.imagePreview = {
          visible: true,
          src: file.url,
          alt: file.filename || '附件图片',
          x: x,
          y: y
        }
      }
    },
    hideImagePreview() {
      this.imagePreview.visible = false
    },
    initTemp() {
      return {
        crm_order_id: this.order_data.id,
        transaction_date: new Date(),
        transaction_type: '产品成本支出',
        amount: 0,
        currency: 'CNY',
        is_income: false,
        category: '物流费用',
        payment_method: '',
        status: 'pending',
        reference_number: '',
        notes: '',
        vendor_or_customer: '',
        expected_payment_date: null,
        actual_payment_date: null,
        is_reconciled: false,
        reconciliation_date: null,
        attachment: null,
        crmfiles: []
      }
    },
    handleGetFinanceCategoy() {
      ShowProjectAttr(null, qs.stringify({ name: '财务费用类型' })).then(response => {
        this.finance_categories = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleGetFinanceTransactionTypes() {
      ShowProjectAttr(null, qs.stringify({ name: '财务交易类型' })).then(response => {
        this.finance_transactiontypes = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    handleInsertFile(item) {
      if (!this.temp.crmfiles) {
        this.temp.crmfiles = []
      }

      // 检查是否已存在（优先使用ID，否则使用URL）
      const existingIndex = this.temp.crmfiles.findIndex(file =>
        (file.id && item.id && file.id === item.id) ||
        (file.url === item.url)
      )

      if (existingIndex === -1) {
        // 现在后端返回完整的CRMFile对象，直接使用即可
        this.temp.crmfiles.push(item)
        this.$message.success(`已添加文件: ${item.filename}`)
      } else {
        this.$message.warning('文件已存在，未重复添加')
      }
    },
    handleEditFromTable(row) {
      this.temp = { ...this.initTemp(), ...row }
      this.action = 'edit'
      this.childFormVisible = true
    },
    handleDeleteFromTable(row) {
      // 防止财务信息丢失，不允许直接删除，需要联系管理员
      this.$alert(
        `财务记录 ID：${row.id}\n\n为防止重要财务信息丢失，请联系系统管理员进行删除操作。\n\n请将此ID提供给管理员以便处理。`,
        '删除提示',
        {
          confirmButtonText: '我知道了',
          type: 'warning',
          showClose: false
        }
      )
    },
    handleShowEdit() {
      this.temp = this.initTemp()
      this.childFormVisible = true
      this.action = 'create'
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        crm_order_id: this.order_data.id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleReconciled(row) {
      UserPutFinance(row.id, { 'is_reconciled': row.is_reconciled }).then(response => {
        row.is_reconciled = !row.is_reconciled
        this.notify('对账成功')
      })
    },
    confirm() {
      this.editloading = true
      const action = this.action === 'create' ? Post
        : (data) => Put(this.temp.id, data)

      action(this.temp).then(() => {
        this.childFormVisible = false
        this.editloading = false
        this.$emit('reload')
        this.notify(this.action === 'edit' ? '修改成功' : '添加成功')
        this.getList()
      }).catch(err => {
        console.log(err)
        this.editloading = false
      })
    },
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    notify(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: 2000
      })
    },
    // 文件上传相关方法
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleCurrencyConvert() {
      const amount = this.temp.amount
      const currency = this.temp.currency

      if (!amount || amount <= 0) {
        this.$message.warning('请先输入有效金额')
        return
      }

      if (!currency) {
        this.$message.warning('请先输入货币类型')
        return
      }

      // 设置转换表单数据并打开对话框
      this.convertForm = {
        originalAmount: amount,
        originalCurrency: currency,
        targetCurrency: 'CNY',
        exchangeRate: 1
      }
      this.convertResult = null
      this.convertDialogVisible = true

      // 从后台查询汇率
      this.fetchExchangeRate(currency, 'CNY')
    },
    handleConvertConfirm() {
      this.convertResult = null
      const amount = this.convertForm.originalAmount
      const sourceCurrency = this.convertForm.originalCurrency
      const targetCurrency = this.convertForm.targetCurrency
      const exchangeRate = this.convertForm.exchangeRate || 1

      if (!amount || amount <= 0) {
        this.$message.warning('请先输入有效金额')
        return
      }

      if (!exchangeRate || exchangeRate <= 0) {
        this.$message.warning('请输入有效汇率')
        return
      }

      if (sourceCurrency === targetCurrency) {
        this.$message.info('原始货币和目标货币相同，无需转换')
        this.convertResult = {
          source_amount: amount,
          source_currency: sourceCurrency,
          target_amount: amount,
          target_currency: targetCurrency
        }
        return
      }

      // 前台计算汇率转换
      const targetAmount = (amount * exchangeRate).toFixed(2)
      this.convertResult = {
        source_amount: amount,
        source_currency: sourceCurrency,
        target_amount: targetAmount,
        target_currency: targetCurrency
      }
    },
    handleApplyConversion() {
      if (this.convertResult) {
        if (this.currentConvertRow) {
          // 如果是从表格行触发的转换，更新数据库
          const convertedAmount = parseFloat(parseFloat(this.convertResult.target_amount).toFixed(2))
          const updateData = {
            amount: convertedAmount,
            currency: this.convertResult.target_currency
          }

          Put(this.currentConvertRow.id, updateData)
            .then(response => {
              if (response.success) {
                // 更新本地数据
                this.currentConvertRow.amount = convertedAmount
                this.currentConvertRow.currency = this.convertResult.target_currency
                this.$message.success('汇率转换并保存成功')
                this.convertDialogVisible = false
                this.currentConvertRow = null
              } else {
                this.$message.error('保存失败')
              }
            })
            .catch(error => {
              console.error('保存失败:', error)
              this.$message.error('保存失败')
            })
        } else {
          // 如果是从表单触发的转换，只更新表单
          this.temp.amount = parseFloat(parseFloat(this.convertResult.target_amount).toFixed(2))
          this.temp.currency = this.convertResult.target_currency
          this.convertDialogVisible = false
          this.$message.success('汇率转换已应用')
        }
      }
    },
    handleTableRowConvert(row) {
      // 设置转换表单数据并打开对话框
      this.convertForm = {
        originalAmount: row.amount,
        originalCurrency: row.currency,
        targetCurrency: 'CNY',
        exchangeRate: 1
      }
      this.convertResult = null
      this.currentConvertRow = row // 保存当前要转换的行数据
      this.convertDialogVisible = true

      // 从后台查询汇率
      this.fetchExchangeRate(row.currency, 'CNY')
    },
    fetchExchangeRate(sourceCurrency, targetCurrency) {
      if (sourceCurrency === targetCurrency) {
        this.convertForm.exchangeRate = 1
        this.exchangeRateSource = '本地配置'
        return
      }

      // 查询汇率配置
      const params = {
        source_currency: sourceCurrency,
        target_currency: targetCurrency,
        is_active: true
      }

      GetExchangeRate(null, qs.stringify(params))
        .then(response => {
          if (response.success && response.data.data && response.data.data.length > 0) {
            // 找到匹配的汇率
            const rate = response.data.data[0]
            this.convertForm.exchangeRate = parseFloat(rate.exchange_rate)
            this.exchangeRateSource = `API: ${rate.source_currency} -> ${rate.target_currency} (汇率: ${rate.exchange_rate})`
            // 自动计算一次转换结果
            this.handleConvertConfirm()
          } else {
            // 如果没有找到汇率配置，使用默认值
            this.convertForm.exchangeRate = this.getDefaultExchangeRate(sourceCurrency)
            this.exchangeRateSource = '本地配置'
            this.$message.warning(`未找到 ${sourceCurrency} 到 ${targetCurrency} 的汇率配置，使用默认汇率`)
            // 使用默认汇率也计算一次
            this.handleConvertConfirm()
          }
        })
        .catch(error => {
          console.error('获取汇率失败:', error)
          this.convertForm.exchangeRate = this.getDefaultExchangeRate(sourceCurrency)
          this.exchangeRateSource = '本地配置'
          this.$message.warning('获取汇率失败，使用默认汇率')
          // 使用默认汇率计算一次
          this.handleConvertConfirm()
        })
    },
    getDefaultExchangeRate(currency) {
      // 提供一些默认汇率作为备用
      const defaultRates = {
        'USD': 7.2,
        'EUR': 7.8,
        'GBP': 9.1,
        'JPY': 0.048,
        'HKD': 0.92,
        'CAD': 5.3,
        'AUD': 4.8,
        'CHF': 8.1,
        'SGD': 5.4,
        'KRW': 0.0055
      }
      return defaultRates[currency] || 1
    },
    handleExchangeRateChange() {
      // 当汇率改变时，如果已有转换结果，重新计算
      if (this.convertResult) {
        this.handleConvertConfirm()
      }
    },
    getMostFrequentCurrency(arr) {
      const frequency = {}
      let maxCount = 0
      let mostFrequent = null

      for (const item of arr) {
        frequency[item] = (frequency[item] || 0) + 1
        if (frequency[item] > maxCount) {
          maxCount = frequency[item]
          mostFrequent = item
        }
      }
      return mostFrequent
    }
  }
}
</script>

<style scoped>
.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 调整图标之间的间距 */
}

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120px; /* 调整每个文件项的宽度 */
}

.file-icon {
  height: 80px;
  width: 80px;
}

.file-name {
  margin-top: 5px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
}

/* 文件列表显示样式 */
.file-list-display {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  min-height: 60px;
}

/* 添加小尺寸文件图标样式 */
.file-list-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 5px;
}

.file-item-inline {
  display: flex;
  align-items: center;
  gap: 3px;
  padding: 2px 5px;
  background: #f5f5f5;
  border-radius: 3px;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.2s;
}

.file-item-inline:hover {
  background: #e0e0e0;
  transform: scale(1.05);
}

.file-icon-small {
  height: 16px;
  width: 16px;
  flex-shrink: 0;
}

.file-name-small {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 11px;
  color: #666;
}
.mt-dialog >>> span.el-dialog__title {
  word-break: normal;
  width: auto;
  display: block;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow: hidden;
}

/* 添加新的样式 */
.finance-form >>> .el-form-item {
  margin-bottom: 18px;
}

.finance-form >>> .el-form-item__label {
  padding-right: 12px;
  font-weight: 500;
}

.finance-form >>> .el-input-number {
  width: 100%;
}

.finance-form >>> .el-input-number .el-input__inner {
  text-align: left;
}

.finance-form >>> .el-select {
  width: 100%;
}

.finance-form >>> .el-date-editor.el-input {
  width: 100%;
}

.form-footer {
  margin-top: 20px;
}

.form-footer .el-button {
  padding: 10px 20px;
  min-width: 100px;
}

/* 隐藏表格底部的多余边框线 */
.el-table {
  border-bottom: none !important;
}

.el-table::after {
  display: none !important;
}

.el-table__body-wrapper {
  border-bottom: none !important;
}
</style>

<style>
/* 图片hover预览样式 - 不使用scoped以便全局显示 */
.image-hover-preview {
  position: fixed;
  z-index: 9999;
  width: 300px;
  max-height: 400px;
  border: 3px solid #409eff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
  background: white;
  pointer-events: none;
  padding: 10px;
}

.image-hover-preview img {
  width: 100%;
  height: auto;
  object-fit: contain;
  display: block;
  border-radius: 4px;
}
</style>
